<template>
    <LayoutWrap class="auth">
        <el-form :inline="true" :model="formSearch" ref="ruleForm" class="demo-form-inline">
            <el-form-item prop="name" label="用户名">
                <el-input
                    v-model="formSearch.name"
                    placeholder="请输入名称"
                    :style="{width: formInputWidth}"
                    clearable
                    @change="handleSearch"
                    @keyup.enter="handleSearch"
                ></el-input>
            </el-form-item>
            <el-form-item prop="roleId" label="角色">
                <el-select
                    v-model="formSearch.roleId"
                    clearable
                    placeholder="请选择角色"
                    :style="{width: formInputWidth}"
                    @change="handleSearch"
                    @keyup.enter="handleSearch"
                >
                    <template v-for="item in optionsRoles">
                        <el-option :label="item.label" :value="item.value" :key="item.value"></el-option>
                    </template>
                </el-select>
            </el-form-item>

            <!-- <el-form-item>
                <el-button type="default" @click="$refs['ruleForm'].resetFields()">重置</el-button>
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item> -->
        </el-form>
        <ul v-if="isOperation" class="list-head">
            <li class="list-head-item">
                <el-button @click="handleAddUser" :disabled="!isOperation" type="primary">添加用户</el-button>
            </li>
        </ul>
        <el-table :data="tableData" border :default-sort="{prop: 'date', order: 'descending'}" style="width: 100%">
            <el-table-column prop="name" label="用户名"> </el-table-column>
            <el-table-column prop="roles" label="角色">
                <template v-slot="{row}">
                    <span v-for="item in row.roles" :key="item.id"> {{ item.name }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="email" label="邮箱"> </el-table-column>
            <el-table-column prop="date" label="创建日期"> </el-table-column>
            <el-table-column prop="remark" label="备注"> </el-table-column>
            <el-table-column align="center" label="操作">
                <template v-slot="{row}">
                    <!-- <el-button @click="handleDetail(row)" type="text">
                        查看
                    </el-button> -->
                    <el-button @click="handleEdit(row)" type="text">
                        编辑
                    </el-button>
                    <el-button :disabled="!isOperation || row.isRoot" @click="handleShowDeleteDialog(row)" type="text">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <Pagination
            :page-size.sync="formSearch.pageSize"
            :page.sync="formSearch.page"
            :total="formSearch.count"
            @change="onChangePage"
        />
        <UserDialog
            title="添加用户"
            @on-ok="getList"
            :data-source="dataSourceAdd"
            :options-roles="optionsRoles"
            :visible.sync="userDialogVisible"
        >
        </UserDialog>
        <UserDialog
            key="编辑用户"
            title="编辑用户"
            @on-ok="getList"
            :data-source="dataSourceEdit"
            :options-roles="optionsRoles"
            :visible.sync="userDialogVisibleEdit"
        >
        </UserDialog>
        <TheElDialog title="删除用户" :visible.sync="dialogVisible">
            <span>你确定删除 {{ currentRow.name }} 吗？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button :loading="dialogLoading" type="primary" @click="handleDelete(currentRow)">确 定</el-button>
            </span>
        </TheElDialog>
    </LayoutWrap>
</template>
<script>
import {formInputWidth} from '@/styles/variables.scss';
import {getUsers, deleteUsers} from '@/api/auth';
import {getRoles, getRolesByIdPermission} from '@/api/role';
import {getPermissions} from '@/api/common';
import UserDialog from './UserDialog';
import {mixinIsOperation} from '@/mixins';

export default {
    name: 'auth',
    components: {UserDialog},
    mixins: [mixinIsOperation],
    data() {
        return {
            formInputWidth,
            optionsRoles: [],
            // 检索数据
            formSearch: {
                name: '',
                roleId: '',
                count: 0, // 总条数
                pageSize: 10, // 一页多少条
                page: 1 // 当前第几页
            },
            // 新建用户弹窗
            userDialogVisible: false,
            // 编辑用户
            userDialogVisibleEdit: false,
            // 查看详情
            userDialogVisibleDetail: false,
            // 删除用户
            dialogVisible: false,
            // 操作用户
            currentRow: {},
            // 删除用户loading
            dialogLoading: false,
            // 添加用户
            dataSourceAdd: {
                id: undefined, // 用户id
                roleId: [], // 角色id
                name: '', // 用户名
                email: '', // 邮箱
                password: '', // 密码
                password2: '', // 确认密码
                remark: '', // 备注
                modelPermission: {
                    childModules: [],
                    functionMap: {},
                    parentModules: [],
                    selectedFunctions: [],
                    selectedModules: []
                } // 权限
            },
            // 编辑用户
            dataSourceEdit: {
                id: undefined, // 用户id
                roleId: [], // 角色id
                name: '', // 用户名
                email: '', // 邮箱
                password: '', // 密码
                password2: '', // 确认密码
                remark: '', // 备注
                modelPermission: {
                    childModules: [],
                    functionMap: {},
                    parentModules: [],
                    selectedFunctions: [],
                    selectedModules: []
                } // 权限
            },
            // 权限列表数据
            permission: {},
            // 列表数据
            tableData: [
                // {
                //     id: '22314',
                //     email: '123142134',
                //     name: 'mrli',
                //     password: '******',
                //     roles: [{id: '1234', name: '管理员'}]
                // },
                // {
                //     id: '22314',
                //     email: '123142134',
                //     name: 'test',
                //     password: '******',
                //     roles: [{id: '1235', name: '普通用户'}]
                // }
            ]
        };
    },
    created() {
        this.getList();
        this.handleGetRolesOptions();
        this.handleGetPermissions();
    },
    methods: {
        onChangePage(value) {
            this.formSearch = {...this.formSearch, ...value};
            this.getList();
        },
        // 获取角色 [{label: 'name', value: 2}]
        handleGetRolesOptions() {
            getRoles({types: 'options'}).then(({data: res}) => {
                if (res.status === 200) {
                    this.optionsRoles = res.data || [];
                }
            });
        },
        // 获取权限 列表
        handleGetPermissions() {
            getPermissions().then(({data: res}) => {
                if (res.status === 200) {
                    const {childModules, functionMap, parentModules, selectedFunctions, selectedModules} = res;
                    this.permission = {childModules, functionMap, parentModules, selectedFunctions, selectedModules};
                }
            });
        },
        // 搜索
        handleSearch() {
            this.formSearch = {...this.formSearch, page: 1, pageSize: 10};
            this.getList();
        },
        // 获取列表数据
        getList() {
            const {name, roleId, pageSize, page} = this.formSearch;
            const newItem = {name, roleId, pageSize, page};
            getUsers(newItem).then(({data: res}) => {
                if (res.status === 200) {
                    const {data, count, page, pageSize} = res;
                    this.tableData = data;
                    this.formSearch = {...this.formSearch, page, pageSize, count};
                }
            });
        },
        // 添加用户
        async handleAddUser() {
            this.userDialogVisible = true;
            const permission = {...this.permission};
            this.dataSourceAdd = {...this.dataSourceAdd, modelPermission: permission};
        },
        // 编辑用户
        async handleEdit(row) {
            this.userDialogVisibleEdit = true;
            const roleId = row.roles.map(i => i.id).join(',');
            const {
                data: {data, status}
            } = await getRolesByIdPermission(roleId);
            if (status === 200) {
                this.dataSourceEdit = {...row, password2: row.password, modelPermission: data};
            }
        },
        // 弹出删除弹窗
        handleShowDeleteDialog(row) {
            // 展示删除弹窗
            this.dialogVisible = true;
            this.currentRow = row;
        },
        // 删除用户
        handleDelete(row) {
            this.dialogLoading = true;
            deleteUsers(row._id)
                .then(res => {
                    this.dialogVisible = false;
                    this.$message({showClose: true, type: 'success', message: '删除成功'});
                    this.getList();
                    this.dialogLoading = false;
                })
                .catch(err => {
                    this.$message({showClose: true, type: 'error', message: '删除失败'});
                    console.log('err :', err);
                    this.dialogVisible = false;
                    this.dialogLoading = false;
                });
        }
    }
};
</script>

<style lang="scss" scoped>
// .auth {
// }
</style>
